package com.xmy.cultivate.realm;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.xmy.cultivate.entity.Admin;
import com.xmy.cultivate.entity.Organization;
import com.xmy.cultivate.service.IAdminService;
import com.xmy.cultivate.service.IAppointSchoolService;
import com.xmy.cultivate.service.IOrganizationService;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

public class WechatRealm extends AuthorizingRealm {

    public void setName(String name) {
        super.setName("wechatRealm");
    }

    @Autowired
    private IAdminService iAdminService;

    @Autowired
    private IAppointSchoolService iAppointSchoolService;

    @Autowired
    private IOrganizationService iOrganizationService;


    /**
     * 授权方法
     *      操作的时候，判断用户是否具有响应的权限
     *          先认证 -- 安全数据
     *          再授权 -- 根据安全数据获取用户具有的所有操作权限
     *
     *
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        //1.获取已认证的用户数据
        Admin admin = (Admin) principalCollection.getPrimaryPrincipal();//得到唯一的安全数据
        //2.根据用户数据获取用户的权限信息（所有角色，所有权限）
        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
        Set<String> roles = new HashSet<>();//所有角色
        Set<String> perms = new HashSet<>();//所有权限
        /*for (Role role : user.getRoles()) {
            roles.add(role.getName());
            for (Permission perm : role.getPermissions()) {
                perms.add(perm.getCode());
            }
        }*/
        perms.add("COURSE-FINDBYID1");
        info.setStringPermissions(perms);
        info.setRoles(roles);
        return info;
        //return null;
    }

    /**
     * 认证方法
     *  参数：传递的用户名密码
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        //1.获取登录的用户名密码（token）
        UsernamePasswordToken upToken = (UsernamePasswordToken) authenticationToken;
        String username = upToken.getUsername();
        String password = new String( upToken.getPassword());

        //System.out.print("username:"+username);
        //System.out.print("password:"+password);

        //2.根据用户名查询数据库
        QueryWrapper<Admin> queryWrapper =  new QueryWrapper<>();

        queryWrapper.eq("account",username);
        queryWrapper.eq("pwd",password);

        Admin admin = iAdminService.getOne(queryWrapper);
        //3.判断用户是否存在或者密码是否一致
        if(admin != null) {
            //管辖校区
            List<Long> appointIdList = new ArrayList<>();
            if(admin.getIsSuper() == 1 || admin.getGovernMode()==1){
                QueryWrapper<Organization> organizationQueryWrapper = new QueryWrapper<>();
                organizationQueryWrapper.eq("type",1);
                appointIdList = iOrganizationService.getOrganiztionId(organizationQueryWrapper);
            }else {
                appointIdList =  iAppointSchoolService.getSchoolIdListForForId(admin.getId(),2);
            }

            //System.out.print("appointIdList");
            //System.out.print(appointIdList);
            admin.setSchoolIdList(appointIdList);

            //4.如果一致返回安全数据
            //构造方法：安全数据，密码，realm域名
            SimpleAuthenticationInfo info = new SimpleAuthenticationInfo(admin,admin.getPwd(),this.getName());
            return info;
        }
        //5.不一致，返回null（抛出异常）
        return null;
    }
}
